package top.yaofengqiao.springcloudsimple.web.starter.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.yaofengqiao.springcloudsimple.web.starter.annatation.SysLog;
import top.yaofengqiao.springcloudsimple.web.starter.service.ISysLogService;
import top.yaofengqiao.springcloudsimple.web.starter.util.OauthUtil;
import top.yaofengqiao.springcloudsimple.web.starter.util.OperatorLog;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author yfq
 * @date 15:59
 * @description
 */
@Slf4j
@Aspect
public class SysLogAspect {
    @Resource
    private ISysLogService sysLogService;

    @Around("@annotation(sysLog)")
    public Object handle(ProceedingJoinPoint joinPoint, SysLog sysLog) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed(joinPoint.getArgs());
        long end = System.currentTimeMillis();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) return result;

        try {
            HttpServletRequest request = requestAttributes.getRequest();
            OperatorLog operatorLog = OperatorLog.builder()
                    .traceId(UUID.randomUUID().toString().replace("-", ""))
                    .userId(OauthUtil.currentUserId())
                    .requestMethod(sysLog.method().toString())
                    .time(end - start)
                    .uri(request.getRequestURI())
                    .ip(request.getRemoteAddr())
                    .build();
            sysLogService.saveSysLog(operatorLog);
        } catch (Exception e) {
            log.warn("审计日志记录异常：", e);
        }

        return result;
    }

}
